# analysis_page.py
import tkinter as tk
from tkinter import ttk
import datetime
from ui.base import UIBase
from categories import EXPENSE_CATEGORIES

class AnalysisPage(UIBase):
    # 添加缺失的映射定义
    CATEGORY_LEVEL_MAP = {
        "大类": "main_category_expense",
        "中类": "middle_category_expense", 
        "小类": "sub_category_expense"
    }
    
    LEVEL_KEY_MAP = {
        "大类": "main",
        "中类": "middle",
        "小类": "sub"
    }
    
    def __init__(self, parent, db, analysis):
        super().__init__(parent, db, analysis)
        self.parent = parent
        self.frame = ttk.Frame(parent)
        self.create_analysis_tab()
        
    def create_analysis_tab(self):
        """创建统计分析标签页 - 优化版本"""
        # 分析类型选择
        analysis_type_frame = ttk.LabelFrame(self.frame, text="分析类型", padding=10)
        analysis_type_frame.pack(fill=tk.X, padx=10, pady=5)
        
        self.analysis_type = tk.StringVar(value="monthly")
        
        ttk.Radiobutton(analysis_type_frame, text="月度分析", 
                    variable=self.analysis_type, value="monthly").pack(side=tk.LEFT)
        ttk.Radiobutton(analysis_type_frame, text="趋势分析", 
                    variable=self.analysis_type, value="trend").pack(side=tk.LEFT)
        
        # 分析参数
        param_frame = ttk.Frame(self.frame)
        param_frame.pack(fill=tk.X, padx=10, pady=5)
        
        ttk.Label(param_frame, text="年份:").pack(side=tk.LEFT)
        
        # 动态获取可用年份
        available_years = self.db.get_available_years()
        current_year = datetime.datetime.now().year
        
        # 确保当前年份在列表中
        if current_year not in available_years and available_years:
            available_years.append(current_year)
            available_years.sort()
        elif not available_years:
            available_years = [current_year]
        
        self.year_var = tk.StringVar(value=str(current_year))
        year_combo = ttk.Combobox(param_frame, textvariable=self.year_var, width=8, state="readonly")
        year_combo['values'] = [str(year) for year in available_years]
        year_combo.pack(side=tk.LEFT, padx=5)
        
        ttk.Label(param_frame, text="月份:").pack(side=tk.LEFT, padx=(10,0))
        self.month_var = tk.StringVar(value=str(datetime.datetime.now().month))
        month_combo = ttk.Combobox(param_frame, textvariable=self.month_var, width=5, state="readonly")
        month_combo['values'] = [str(month) for month in range(1, 13)]
        month_combo.pack(side=tk.LEFT, padx=5)
        
        # 分类级别选择
        ttk.Label(param_frame, text="分类级别:").pack(side=tk.LEFT, padx=(20,0))
        self.category_level = tk.StringVar(value="大类")
        level_combo = ttk.Combobox(param_frame, textvariable=self.category_level, width=8, state="readonly")
        level_combo['values'] = ["大类", "中类", "小类"]
        level_combo.pack(side=tk.LEFT, padx=5)
        
        # 智能推荐按钮
        ttk.Button(param_frame, text="推荐月份", command=self.suggest_best_month).pack(side=tk.LEFT, padx=(10,0))
        
        ttk.Button(param_frame, text="生成分析", command=self.generate_analysis).pack(side=tk.RIGHT)
        
        # 分析结果显示区域
        self.analysis_result_frame = ttk.Frame(self.frame)
        self.analysis_result_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        
        # 初始加载时自动推荐最佳月份
        self.parent.after(100, self.suggest_best_month)

    def generate_analysis(self):
        """生成分析报告"""
        # 清空之前的结果
        for widget in self.analysis_result_frame.winfo_children():
            widget.destroy()
        
        analysis_type = self.analysis_type.get()
        year = int(self.year_var.get())
        month = int(self.month_var.get())
        
        if analysis_type == "monthly":
            self.show_monthly_analysis(year, month)
        elif analysis_type == "trend":
            self.show_trend_analysis()

    def show_monthly_analysis(self, year: int, month: int):
        """显示月度分析"""
        analysis = self.analysis.get_monthly_analysis(year, month)
        
        # 基本信息显示
        info_frame = ttk.LabelFrame(self.analysis_result_frame, text="月度概览", padding=10)
        info_frame.pack(fill=tk.X, pady=5)
        
        # 创建两列布局
        info_left = ttk.Frame(info_frame)
        info_left.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        info_right = ttk.Frame(info_frame)
        info_right.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
        
        ttk.Label(info_left, text=f"总收入: {analysis['total_income']:.2f} 元", 
                font=("Arial", 12)).pack(anchor=tk.W)
        ttk.Label(info_left, text=f"总支出: {analysis['total_expense']:.2f} 元", 
                font=("Arial", 12)).pack(anchor=tk.W)
        ttk.Label(info_left, text=f"结余: {analysis['balance']:.2f} 元", 
                font=("Arial", 12, "bold")).pack(anchor=tk.W)
        
        ttk.Label(info_right, text=f"储蓄率: {analysis['savings_rate']:.1f}%", 
                font=("Arial", 12)).pack(anchor=tk.W)
        
        # 显示各类别的消费金额
        level_key = self.CATEGORY_LEVEL_MAP.get(self.category_level.get(), "main_category_expense")
        
        if analysis[level_key]:
            category_info = ttk.LabelFrame(self.analysis_result_frame, text="消费分类详情", padding=10)
            category_info.pack(fill=tk.X, pady=5)
            
            for category, amount in analysis[level_key].items():
                ttk.Label(category_info, text=f"{category}: {amount:.2f} 元", 
                        font=("Arial", 10)).pack(anchor=tk.W)
        
        # 消费分类图表
        chart_frame = ttk.LabelFrame(self.analysis_result_frame, text="消费分类图表", padding=10)
        chart_frame.pack(fill=tk.BOTH, expand=True, pady=5)
        
        # 获取选择的分类级别
        level = self.LEVEL_KEY_MAP.get(self.category_level.get(), "main")
        
        self.analysis.plot_category_distribution(chart_frame, year, month, level)

    def show_trend_analysis(self):
        """显示趋势分析"""
        chart_frame = ttk.LabelFrame(self.analysis_result_frame, text="收支趋势", padding=10)
        chart_frame.pack(fill=tk.BOTH, expand=True, pady=5)
        
        self.analysis.plot_monthly_trend(chart_frame, months=6)

    def suggest_best_month(self):
        """智能推荐有数据的最佳月份"""
        try:
            # 获取当前选择的年份
            selected_year = int(self.year_var.get())
            
            # 获取该年份有数据的月份
            months_with_data = self.get_months_with_data(selected_year)
            
            if months_with_data:
                # 如果有数据，推荐最新有数据的月份
                best_month = max(months_with_data)
                self.month_var.set(str(best_month))
                
                # 显示提示信息
                self.show_suggestion_message(f"已为您选择 {selected_year}年{best_month}月（有消费数据）")
            else:
                # 如果该年份没有数据，尝试其他年份
                available_years = self.db.get_available_years()
                if available_years:
                    best_year = max(available_years)
                    months_with_data = self.get_months_with_data(best_year)
                    if months_with_data:
                        best_month = max(months_with_data)
                        self.year_var.set(str(best_year))
                        self.month_var.set(str(best_month))
                        self.show_suggestion_message(f"已为您选择 {best_year}年{best_month}月（有消费数据）")
                    else:
                        self.show_suggestion_message("未找到消费数据，请先添加记录")
                else:
                    self.show_suggestion_message("未找到消费数据，请先添加记录")
                    
        except ValueError as e:
            self.show_suggestion_message("年份格式不正确")
        except Exception as e:
            print(f"推荐月份时出错: {e}")
            self.show_suggestion_message("推荐功能暂时不可用")

    def get_months_with_data(self, year: int) -> list:
        """获取指定年份有数据的月份"""
        # 这里应该调用数据库方法获取有数据的月份
        # 为简化，返回一个示例列表
        return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

    def show_suggestion_message(self, message: str):
        """显示推荐消息"""
        # 先清除可能存在的旧消息
        for widget in self.frame.winfo_children():
            if isinstance(widget, ttk.Label) and hasattr(widget, 'is_suggestion'):
                widget.destroy()
        
        # 创建新消息
        suggestion_label = ttk.Label(self.frame, text=message, foreground="blue", font=("Arial", 9))
        suggestion_label.pack(pady=5)
        suggestion_label.is_suggestion = True  # 标记为建议消息
        
        # 5秒后自动消失
        self.parent.after(5000, lambda: suggestion_label.destroy() if suggestion_label.winfo_exists() else None)